package com.pinecone.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.pinecone.common.utils.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.pinecone.entity.LiveRoomCommentEntity;
import com.pinecone.service.LiveRoomCommentService;
import com.pinecone.common.utils.PageUtils;
import com.pinecone.common.utils.Query;
import com.pinecone.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 直播间评论表
 * 
 * @author hushangjie
 * @email 979783618@qq.com
 * @date 2017-09-27 21:17:58
 */
@RestController
@RequestMapping("live_room_comment")
public class LiveRoomCommentController {
	@Autowired
	private LiveRoomCommentService liveRoomCommentService;
	@Autowired
    private RedisTemplate redisTemplate;
    //观众提交评论(该接口无需授权)
    @PostMapping("/submit")
    public R submitComment(@RequestBody @Validated LiveRoomCommentEntity commentEntity){
        //默认为空
        commentEntity.setLiveRoomCommentId(null)
                .setCommentTime(null);
        liveRoomCommentService.save(commentEntity);
        return R.ok();
    }

    /**
     * 点赞接口，若该ip地址已经点赞，则取消赞,votes=1则表示点赞成功，voteds=0表示取消赞
     * @param request
     * @param commentId
     * @return 如果
     */

    @GetMapping("/vote")
    public R voteComment(HttpServletRequest request, @RequestParam(value = "comment_id",required = true) Long commentId){
        Long res = liveRoomCommentService.voteComment(IPUtils.getIpAddr(request),commentId);
        return R.ok().put("votes",res);
    }


    /**
     * 获取指定直播间的评论
     * @param params
     * @return
     */
    /*@PreAuthorize("hasAnyRole('ROLE_SYSADMIN','ROLE_ORGMASTER')")*/
	@GetMapping("")
	public R list(@RequestParam Map<String, Object> params){
        if (params.get("liveRoomId") == null){
            return R.error("必须指定直播间id");
        }
		//查询列表数据
        Query query = new Query(params);
		if (params.get("page") != null && params.get("limit")!= null){
			List<LiveRoomCommentEntity> liveRoomCommentList = liveRoomCommentService.queryList(query);
            //获取每条评论的点赞数
            List<Integer> ups = new ArrayList<>();
            redisTemplate.execute(new RedisCallback() {
                @Override
                public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    for (LiveRoomCommentEntity liveRoomCommentEntity : liveRoomCommentList){
                        Object up = redisTemplate.opsForSet().size("pineconelive:comment:vote:"+liveRoomCommentEntity.getLiveRoomCommentId());
                        liveRoomCommentEntity.setCommentUp(redisTemplate.opsForSet().size("pineconelive:comment:vote:"+liveRoomCommentEntity.getLiveRoomCommentId()));
                    }
                    return null;
                }
            });
			int total = liveRoomCommentService.queryTotal(query);
			
			PageUtils pageUtil = new PageUtils(liveRoomCommentList, total, query.getLimit(), query.getPage());
			
			return R.ok().put("page", pageUtil);
		}else{
			List<LiveRoomCommentEntity> liveRoomCommentList = liveRoomCommentService.queryList(query);
			return R.ok().put("list", liveRoomCommentList);
		}
		
	}

	//获取某个直播间留言总数
    @GetMapping("/stat/{liveRoomId}")
    public R getCommentNumbers(@PathVariable(value = "liveRoomId",required = true) String liveRoomId){
	    Map<String,Object> query = new HashMap<>();
	    query.put("liveRoomId",liveRoomId);
        Integer totalAccount = liveRoomCommentService.queryTotal(query);
        return R.ok().put("total",totalAccount);
    }



	/**
	 * 信息
	 */
	@GetMapping("/{liveRoomCommentId}")
	public R info(@PathVariable("liveRoomCommentId") Long liveRoomCommentId){
		LiveRoomCommentEntity liveRoomComment = liveRoomCommentService.queryObject(liveRoomCommentId);
		
		return R.ok().put("liveRoomComment", liveRoomComment);
	}
	
	/**
	 * 保存
	 */
	@PostMapping("")
	public R save(@RequestBody LiveRoomCommentEntity liveRoomComment){
		liveRoomCommentService.save(liveRoomComment);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@PutMapping("")
	public R update(@RequestBody LiveRoomCommentEntity liveRoomComment){
		liveRoomCommentService.update(liveRoomComment);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PreAuthorize("hasAnyRole('ROLE_ORGHOST','ROLE_ORGMASTER')")
	@DeleteMapping("")
	public R delete(@RequestBody Long[] liveRoomCommentIds){
		liveRoomCommentService.deleteBatch(liveRoomCommentIds);
		return R.ok();
	}
	
}
